﻿using System;
using System.Collections.Generic;
using System.Text;
using EricUtility;
using TVOnline;
using TVOnline.Entities;
using System.Net;

namespace WatchSeriesHelper.Entities
{
    public class EpisodeInfo : AbstractLoadingTuple
    {
        private readonly int m_Id;
        private readonly int m_EpisodeId;
        private readonly Dictionary<string, WebsiteSerieInfo> m_WebSites = new Dictionary<string, WebsiteSerieInfo>();
        private readonly Dictionary<KnownWebsite, WebsiteSerieInfo> m_KnownWebSites = new Dictionary<KnownWebsite, WebsiteSerieInfo>();
        private readonly string m_Name;
        private readonly SeasonInfo m_Season;

        private string m_Description = "";

        public int Id { get { return m_Id; } }
        public int EpisodeId { get { return m_EpisodeId; } }
        public SeasonInfo Season { get { return m_Season; } }
        public string Name { get { return m_Name; } }
        public string Description { get { return m_Description; } }
        public string URL { get { return "http://watchseries.eu/episode/" + m_Season.Show.Id + "_s" + m_Season.SeasonId + "_e" + m_EpisodeId + "-" + m_Id + ".html"; } }
        public WebsiteSerieInfo[] WebSites
        {
            get
            {
                WebsiteSerieInfo[] array = new WebsiteSerieInfo[m_WebSites.Count];
                m_WebSites.Values.CopyTo(array, 0);
                return array;
            }
        }
        public int NbSites { get { return m_WebSites.Count; } }

        public EpisodeInfo(SeasonInfo s, int id, int epId, string name)
        {
            m_Season = s;
            m_Id = id;
            m_EpisodeId = epId;
            m_Name = name.Replace("\n","").Trim();
        }

        protected override void OnLoad()
        {
            m_WebSites.Clear();
            m_KnownWebSites.Clear();

            CookieContainer cookies = new CookieContainer();
            string s = EricUtility.Networking.Gathering.GatheringUtility.GetPageSource(URL,cookies);
            string descDiv = "<div class=\"episode-summary\">";
            int iDescDiv = s.IndexOf(descDiv);
            string descTd = "<p>";
            int iDescTd = s.IndexOf(descTd, iDescDiv) + descTd.Length;
            int iDescTdEnd = s.IndexOf("<iframe", iDescTd);
            m_Description = StringUtility.RemoveHTMLTags(WebStringUtility.DecodeString(s.Substring(iDescTd, iDescTdEnd - iDescTd)).Trim());


            s = EricUtility.Networking.Gathering.GatheringUtility.GetPageSource("http://watchseries.eu/getlinks.php?q=" + m_Id + "&domain=all", cookies);

            string deb = "<div class=\"linewrap\" >";
            while (s.IndexOf(deb) >= 0)
            {
                s = s.Substring(s.IndexOf(deb) + deb.Length);
                string siteDeb = "<div class=\"site\">";
                string divFin = "</div>";
                int posSiteDeb = s.IndexOf(siteDeb) + siteDeb.Length;
                int posSiteFin = s.IndexOf(divFin, posSiteDeb);
                string site = s.Substring(posSiteDeb, posSiteFin - posSiteDeb).Trim();
                int posDlDeb = s.IndexOf("<div class=\"download\">", posSiteFin);
                int posUrlFin = 0;
                int posUrlDeb = 0;
                string urlDeb = "<a href=\"../open/cale/";
                string urlFin = "/idepisod/";
                List<string> urls = new List<string>();
                while ((posUrlDeb = s.IndexOf(urlDeb, posUrlFin) + urlDeb.Length) >= 0 && posUrlDeb > posUrlFin && posUrlDeb < posDlDeb)
                {
                    posUrlFin = s.IndexOf(urlFin, posUrlDeb);
                    string url = s.Substring(posUrlDeb, posUrlFin - posUrlDeb);
                    urls.Add(url);
                }
                AddLink(site, urls, cookies);
            }
        }
        public WebsiteInfo KnownWebSite(KnownWebsite t)
        {
            if (!m_KnownWebSites.ContainsKey(t))
                return null;
            return m_KnownWebSites[t];
        }
        private void AddLink( string site, List<string> urls, CookieContainer cookies )
        {
            WebsiteSerieInfo w;
            if (m_WebSites.ContainsKey(site))
                w = m_WebSites[site];
            else
            {
                w = new WebsiteSerieInfo(this, site);
                if (m_WebSites.ContainsKey(w.Name))
                {
                    w = m_WebSites[w.Name];
                }
                else
                {
                    if (w.TypeWebSite != KnownWebsite.Others)
                        m_KnownWebSites.Add(w.TypeWebSite, w);
                    m_WebSites.Add(w.Name, w);
                }
            }
            LinkInfo l = new LinkInfo(w, w.Mirrors.Length+1);
            int count = 1;
            foreach (string s in urls)
                l.AddLink(new LinkPartSerieInfo(l,s,count++,cookies));
            w.AddMirror(l);
        }

        public string LinksToString()
        {
            LoadIfNeeded();
            string str = ">>> " + ToString() + " <<<" + Environment.NewLine + Environment.NewLine;

            foreach (WebsiteSerieInfo site in m_WebSites.Values)
            {
                str += site +Environment.NewLine;
                foreach (LinkInfo link in site.Mirrors)
                {
                    str += "   - " + link + ":" + Environment.NewLine;
                    foreach (LinkPartInfo u in link.Links)
                        str += "       > " + u + Environment.NewLine;
                }
            }
            return str;
        }

        public string DescriptionToString()
        {
            LoadIfNeeded();
            string str = ">>> " + ToString() + " <<<" + Environment.NewLine + Environment.NewLine;

            str += m_Description;
            return str;
        }
        public override string ToString()
        {
            return String.Format("{0:00} - {1}",m_EpisodeId,m_Name);
        }
    }
}
